<template>
  <div class="user-add-container">
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">{{ isEdit ? '编辑用户' : '新增用户' }}</h2>
        <el-button icon="el-icon-back" @click="$router.go(-1)">返回</el-button>
      </div>
    </div>

    <div class="content-container">
      <div class="section-card">
        <div class="section-header">
          <h3>用户信息</h3>
        </div>
        <el-form
          ref="userForm"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="right"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="form.nickname" placeholder="请输入昵称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio label="正常">正常</el-radio>
                  <el-radio label="禁用">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="积分" prop="points">
                <el-input-number
                  v-model="form.points"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 200px"
                ></el-input-number>
                <span class="unit-label">分</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" :rows="4" placeholder="请输入备注信息"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item class="form-actions">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { addUser, getUserDetail, updateUser } from '@/api/user'

export default {
  name: 'UserAdd',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    return {
      isEdit: false,
      loading: false,
      form: {
        id: null,
        username: '',
        nickname: '',
        phone: '',
        status: '正常',
        points: 0,
        remark: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur',
          },
        ],
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' },
        ],
        status: [
          { required: true, message: '请选择用户状态', trigger: 'change' },
        ],
      },
    }
  },
  created() {
    // 获取路由参数，判断是编辑还是新增
    const id = this.$route.query.id
    if (id) {
      this.isEdit = true
      this.fetchUserDetail(id)
    }
  },
  methods: {
    // 获取用户详情
    fetchUserDetail(id) {
      this.loading = true
      getUserDetail(id)
        .then(res => {
          if (res.code === 200 && res.data) {
            this.form = { ...res.data }
          } else {
            this.$message.error(res.message || '获取用户详情失败')
            this.$router.push('/user/list')
          }
        })
        .catch(error => {
          console.error('获取用户详情出错', error)
          this.$message.error('获取用户详情失败')
          this.$router.push('/user/list')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 表单提交
    submitForm() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.loading = true

          // 准备请求数据，根据是否为编辑模式提取不同的字段
          const userData = { ...this.form }

          // 编辑模式下移除不允许更新的字段
          delete userData.id
          // 移除不需要的字段
          if (this.isEdit) {
            delete userData.username
            delete userData.createdAt
            delete userData.updatedAt
          } else {
            // 新增用户时，设置默认密码
            userData.password = '123456'
          }

          const request = this.isEdit
            ? updateUser(this.form.id, userData)
            : addUser(userData)

          request
            .then(res => {
              if (res.code === 200) {
                this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
                this.$router.push('/user/list')
              } else {
                this.$message.error(
                  res.message || (this.isEdit ? '编辑失败' : '新增失败')
                )
              }
            })
            .catch(error => {
              console.error(
                this.isEdit ? '更新用户失败' : '新增用户失败',
                error
              )
              this.$message.error(this.isEdit ? '更新用户失败' : '新增用户失败')
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.userForm.resetFields()
      if (this.isEdit) {
        this.fetchUserDetail(this.form.id)
      }
    },
  },
}
</script>

<style scoped>
.user-add-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: #ffffff;
  border-radius: 8px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section-card {
  background: #ffffff;
  padding: 24px;
  border-radius: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e6eb;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.unit-label {
  margin-left: 10px;
  color: #606266;
}

.form-actions {
  margin-top: 32px;
  text-align: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style> 